<?php

/*
	This file is part of Mandragon.

    Mandragon is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Mandragon is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Mandragon.  If not, see <http://www.gnu.org/licenses/>.
*/

class LoginManager {

	private $db_access;
	private $region_manager;
	private $session_manager;

	public function __construct() {
		$this->db_access = new DbAccessor();
		$this->region_manager = new RegionManager();
		$this->session_manager = new SessionManager();
	}

	public function set_db_accessor($db_access) {
		$this->db_access = $db_access;
	}

	public function set_region_manager($region_manager) {
		$this->region_manager = $region_manager;
	}

	public function set_session_manager($session_manager) {
		$this->session_manager = $session_manager;
	}

	/**
	 * initiate session variables if login info provided
	 */
	function login($justregistered = 0) {

		if ($_SESSION['user_id']) {
			return;
		}

		global $CONFIG;

		if (!$justregistered) {

			$uid = $this->processCookieInfo();
			if($uid)
				$sql = $this->db_access->db_query_select(array(array('pwd', 'user_id', 'title')), array('MEMBER'), "MEMBER.user_id = $uid");

			// 1.b. process login information
			if (isset($_POST['login'])) {

				if (!isset($_POST['password'])) {
					login_catch("no password supplied with login '{$_POST['login']}'");
					return false;
				}

				$login = $_POST['login'];
				$pwd = md5($CONFIG['pwd_prefix'] . $_POST['password'] . $CONFIG['pwd_suffix']);

				$sql = $this->db_access->db_query_select(array(array('pwd', 'user_id', 'title')), array('MEMBER'), 
								   "MEMBER.nick LIKE " . $this->db_access->db_sqlize($_POST['login']));
			}
			
			// 2. check credentials
			$sqlresult = $this->db_access->db_do_query($sql);
		
			if ($this->db_access->db_num_rows($sqlresult) != 1) {
				processSqlResult($_POST['login'], $uid);
				return;
			}
			
			$result = $this->db_access->db_fetch_array($sqlresult);
			
			if (isset($_POST['login']) and ($pwd != $result['pwd'])) {
				login_catch("fout wachtwoord voor account '{$_POST['login']}'");
				return;
			}

			if ($result['title'] == "nog inactief") {
				login_catch("account '{$_POST['login']}' is nog niet geactiveerd. Dit doe je door de link te 
							 volgen in de welkomstmail die je kreeg na je registratie.");
				return;
			}

			$user_id = $result['user_id'];
		
			// 4. update counter
			$ipstring = $_SERVER["REMOTE_ADDR"]." - ".$_SERVER["HTTP_X_FORWARDED_FOR"];
			$sql = $this->db_access->db_query_select(array(array("*")), array('COUNTER'), "user_id = $user_id AND ipstring = " . $this->db_access->db_sqlize($ipstring));
			$sqlresult = $this->db_access->db_do_query($sql);
			
			if ($this->db_access->db_num_rows($sqlresult)) {
				$sql = $this->db_access->db_query_update(array('logins'), array('logins+1'), "COUNTER", "user_id = $user_id AND ipstring = " . $this->db_access->db_sqlize($ipstring));
				$this->db_access->db_do_query($sql);
			} else {
				$sql = $this->db_access->db_query_insert(array('user_id', 'ipstring', 'logins'), array($user_id, $this->db_access->db_sqlize($ipstring), 1), "COUNTER");
				$this->db_access->db_do_query($sql);
			}
		} else {
			$user_id = $justregistered;
		}
		
		// 5. set session variables
		$this->session_manager->session_register();
		$sql = $this->db_access->db_query_select(array(array('*')), array("MEMBER"), "MEMBER.user_id = $user_id"); //0
		$sqlresult = $this->db_access->db_do_query($sql); //1
		$member = $this->db_access->db_fetch_array($sqlresult); //2
		$_SESSION['member'] = $member;
		$_SESSION['user_id'] = $user_id;
		$_SESSION['user_ipstring'] = $ipstring;

		//TODO: register preferences in $CONFIG

		$sql = $this->db_access->db_query_select(array(array("usergroup_id")), array("IN_USERGROUP"), "user_id = $user_id"); //3
		$sqlresult = $this->db_access->db_do_query($sql); //4
		$groups = array();
		while ($result = $this->db_access->db_fetch_array($sqlresult)) { //5
			array_push($groups, $result['usergroup_id']);
		}
		$_SESSION['user_groups'] = $groups;

		// 3. update profiles
		$sql = $this->db_access->db_query_update(array('member_since', 'last_visit'), array('member_since', 'NOW(14)'), 'MEMBER', "user_id = $user_id"); //TODO: remove magic number //6
		$this->db_access->db_do_query($sql); //7
			
		// 6. update cookie
		if ($member['pref_logon_time']) {
			setcookie($CONFIG['cookie_name'], "{$user_id}@@{$pwd}", time() + 86400 * $member['pref_logon_time'], '/'); //TODO: remove magic number
		}
			
		$this->derive_country($user_id);
	}

	function derive_country($user_id) {

		$sqlres = $this->db_access->db_do_query(  //9
				$this->db_access->db_query_select(array(array('*')), array('IN_REGION'), "user_id = $user_id")); //8
		if ($this->db_access->db_num_rows($sqlres)) { //10
			$r = $this->db_access->db_fetch_array($sqlres);
		}
		if ($r['region_id']) {
			$path = $this->region_manager->region_get_region_tree($r['region_id']);
			$c_id = $path[count($path)-1]['region_id'];
			switch($c_id) {
				case 1: $_SESSION['country'] = "BE"; break;
				case 2: $_SESSION['country'] = "NL"; break;
			}
		}
	}

	function processCookieInfo() {
		// 1.a. process cookie information
		global $CONFIG;
		if ($_COOKIE[$CONFIG['cookie_name']] != "") {

			$cookie = explode("@@", $_COOKIE[$CONFIG['cookie_name']]);

			if (count($cookie) != 2) {
				login_catch("cookie beschadigd.");
				setcookie($CONFIG['cookie_name'], "", time() - 3600);
				return;
			}

			list($uid, $pwd) = $cookie;

			// empty cookie means shit
			if ($uid == "")
				login_catch("empty cookie, trying harder");		

			return $uid;
		}
	}

	function processSqlResult($login, $uid) {
		if ($login != "")
			login_catch("account '$login' does not exist");
		else
			login_catch("account #$uid does not exist");
		return;
	}

	/**
	 * destroy session info
	 */
	function logout() {
		global $CONFIG;
		session_unset('user_id', 'user_groups', 'user_ipstring', 'member');
		session_destroy();
		setcookie($CONFIG['cookie_name'], "", time()+8640000, '/');
	}

	/**
	 * catch login errors
	 */
	function login_catch($error) {
		endpage($error);
	}
}

?>
